import React, { useEffect } from 'react';
import { Modal, Form, Input, Select, message, InputNumber } from 'antd';
import PropTypes from 'prop-types';
import { setNetConfig } from '@api/networkConfig';
import { _ } from 'core-js';
import { IP_RE, IP_V6, IP_ADDRESS_MASK } from '@util/constants';
const formItemLayout = {
  labelCol: {
    span: 8
  },
  wrapperCol: {
    span: 16
  }
};
const IPv6Config = [{ value: true, lable: '是' }, { value: false, lable: '否' }];
function EditModal(props) {
  const { form, data, visible } = props;
  const { getFieldDecorator, setFieldsValue, validateFields, getFieldValue } = form;
  useEffect(() => {
    if (data && visible) {
      let fieldsValue = {
        ...data,
        name: data.cnName,
        enableIPv6: data.address_ipv6 || data.gateway6 ? true : false,
        ipv4: data.address_ipv4,
        mask: data.netmask_ipv4,
        gw: data.gateway4,
        ipv6: data.address_ipv6,
        mask6: data.netmask_ipv6,
        gw6: data.gateway6
      };
      setFieldsValue(fieldsValue);
      if (data.address_ipv6 || data.gateway6) {
        setTimeout(() => {
          setFieldsValue(fieldsValue);
        }, 100);
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible]);
  useEffect(() => {}, []);
  const changSelect = item => {
    if (item) {
      setTimeout(() => {
        setFieldsValue({
          ...data,
          name: data.cnName,
          ipv6: data.address_ipv6,
          mask6: data.netmask_ipv6,
          gw6: data.gateway6
        });
      }, 100);
    }
  };
  const onReset = () => {
    form.resetFields();
  };
  const onOk = () => {
    return validateFields(async (err, values) => {
      if (!err) {
        delete values.name;
        delete values.rawname;
        if (!values.gw) {
          if (!data.gateway4) {
            delete values.gw;
          } else {
            values.gw = data.gateway4;
          }
        }
        if (!values.gw6) {
          if (!data.gateway6) {
            delete values.gw6;
          } else {
            values.gw6 = data.gateway6;
          }
        }
        if (values.mask6) {
          values.mask6 = String(values.mask6);
        }
        if (!values.enableIPv6) {
          delete values.gw6;
        }
        try {
          const result = await setNetConfig({
            ...values,
            dev: data.name
          });
          const msg = _.get(result, 'data.data.message');
          if (!msg) {
            message.error('修改失败');
          } else {
            message.success('修改成功');
            onReset();
            props.onOk();
          }
        } catch (error) {
          message.error(_.get(error, 'error.response.data.error') || '修改失败');
          return;
        }
      }
    });
  };
  const onCancel = () => {
    onReset();
    props.onCancel();
  };
  return (
    <>
      <Modal title="编辑网络配置" {...props} onOk={onOk} onCancel={onCancel} maskClosable={false}>
        <Form labelAlign="left">
          <Form.Item {...formItemLayout} label="网口名称" colon={false}>
            {getFieldDecorator('rawname', {
              validateFirst: true
            })(<Input disabled />)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="网口用途" colon={false}>
            {getFieldDecorator('name', {
              validateFirst: true
            })(<Input disabled />)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="IPv4地址" colon={false}>
            {getFieldDecorator('ipv4', {
              rules: [
                {
                  required: true,
                  message: '请输入IPv4地址'
                },
                {
                  pattern: IP_RE,
                  message: '请输入合法的IPv4地址'
                }
              ]
            })(<Input placeholder="请输入IPv4地址" />)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="IPv4子网掩码" colon={false}>
            {getFieldDecorator('mask', {
              rules: [
                {
                  required: true,
                  message: '请输入合法的IPv4子网掩码'
                },
                {
                  pattern: IP_ADDRESS_MASK,
                  message: '请输入合法的IPv4子网掩码'
                }
              ]
            })(<Input placeholder="请输入IPv4子网掩码" />)}
          </Form.Item>
          {data.name !== 'scan0' && (
            <Form.Item {...formItemLayout} label="IPv4网关" colon={false}>
              {getFieldDecorator('gw', {
                rules: [
                  {
                    required: true,
                    message: '请输入IPv4网关'
                  },
                  {
                    pattern: IP_RE,
                    message: '请输入合法的IPv4网关'
                  }
                ]
              })(<Input placeholder="请输入IPv4网关" />)}
            </Form.Item>
          )}
          <Form.Item {...formItemLayout} label="是否启用IPv6" colon={false}>
            {getFieldDecorator('enableIPv6', {})(
              <Select placeholder="请选择是否使用IPv6" onChange={changSelect}>
                {IPv6Config.map(item => (
                  <Select.Option value={item.value} key={item.value}>
                    {item.lable}
                  </Select.Option>
                ))}
              </Select>
            )}
          </Form.Item>
          {getFieldValue('enableIPv6') === true ? (
            <div>
              <Form.Item {...formItemLayout} label="IPv6地址" colon={false}>
                {getFieldDecorator('ipv6', {
                  rules: [
                    {
                      required: true,
                      message: '请输入IPv6地址'
                    },
                    {
                      pattern: IP_V6,
                      message: '请输入合法的IPv6地址'
                    }
                  ]
                })(<Input placeholder="请输入IPv6地址" />)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="IPv6前缀长度" colon={false}>
                {getFieldDecorator('mask6', {
                  rules: [
                    {
                      required: true,
                      message: '长度必须为1-128的整数'
                    }
                  ]
                })(
                  <InputNumber
                    max={128}
                    min={1}
                    placeholder="请输入IPv6前缀长度"
                    style={{ width: '100%' }}
                  />
                )}
              </Form.Item>
              {data.name !== 'scan0' && (
                <Form.Item {...formItemLayout} label="IPv6网关" colon={false}>
                  {getFieldDecorator('gw6', {
                    rules: [
                      {
                        required: true,
                        message: '请输入IPv6网关'
                      },
                      {
                        pattern: IP_V6,
                        message: '请输入合法的IPv6网关'
                      }
                    ]
                  })(<Input placeholder="请输入IPv6网关" />)}
                </Form.Item>
              )}
            </div>
          ) : null}
        </Form>
      </Modal>
    </>
  );
}
EditModal.propTypes = {
  visible: PropTypes.bool,
  data: PropTypes,
  form: PropTypes,
  onOk: PropTypes.func,
  onCancel: PropTypes.func
};
export default Form.create()(EditModal);
